package com.yjf.ljr.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.activity.IjActivity.ID;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.CheckOldMobileClass;
import com.yjf.ljr.dataclass.SendSmsCodeClass;
import com.yjf.ljr.dataclass.VerifySmsCodeDataClass;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;

public class UpdatePhoneActivity extends IjActivity {

	private String mobile;// 手机号码 不展示
	private String viewMobile;// 手机号码 展示用
	static UpdatePhoneActivity instance;

	private String md5UserBaseId;// 验证userBaseId
	private String newMobile;// 新手机号
	
	@ID("webView")
	private WebView webView;
	@ID("llError_webview")
	private LinearLayout mLlError;
	private String modifyMobileUrl;
	private final String RESULT_URL = "userManage/topUp/resultForApp";
    private String appCacheDir;
    private String okReturnStr;	
	private String returnStr; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.updatephonenumber);
		instance = this;
		initControl();

	}

	private void initControl() {

		setLeftBtnClick();
		mobile = getIntent().getStringExtra("mobile");
		viewMobile = getIntent().getStringExtra("viewMobile");
		modifyMobileUrl = getIntent().getStringExtra("modifyMobileUrl");
		setTitleStr("修改绑定手机");	
		
		okReturnStr = CommonData.LOGIN_GOTO_URL+RESULT_URL;
		returnStr = getIntent().getStringExtra("returnStr");
		if(!TextUtils.isEmpty(returnStr)) {
			returnStr = CommonData.LOGIN_GOTO_URL+returnStr;
		}
		
		WebSettings settings = webView.getSettings();
		webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		settings.setSupportZoom(false);
		settings.setBuiltInZoomControls(false);
		settings.setDomStorageEnabled(true);
		settings.setAppCacheMaxSize(1024 * 1024 * 9);// 设置缓冲大小
		appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
		settings.setAppCachePath(appCacheDir);
		settings.setAllowFileAccess(true);
		settings.setAppCacheEnabled(true);
		settings.setJavaScriptEnabled(true);
		settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//		mWvContent.addJavascriptInterface(new JavaScriptInterface(), "bornClient");
		webView.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				if(!TextUtils.isEmpty(returnStr) && !TextUtils.isEmpty(url) && url.startsWith(returnStr)) {
					webView.setVisibility(View.GONE);
				}				
				if (!TextUtils.isEmpty(url) && url.startsWith(okReturnStr) && url.contains("code")) {
					String code = "";
					try{
						code = Uri.parse(url).getQueryParameter("code");
					} catch (Exception e) {
						e.printStackTrace();
					}			
					if("EXECUTE_SUCCESS".equalsIgnoreCase(code)) {
						showToast("修改成功！");
						setResult(RESULT_OK);
					} else {
						String content = Uri.parse(url).getQueryParameter("message");						
						if(!TextUtils.isEmpty(content)) {
							showToast(content);
						} else {
							showToast("修改失败！");
						}
						setResult(RESULT_CANCELED);
					}					
					UpdatePhoneActivity.this.finish();
					return;
				}
				showProgressDialog();
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				dismissProgressDialog();
                mLlError.setVisibility(View.VISIBLE);
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				handler.proceed();
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				dismissProgressDialog();
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if(url.startsWith("tel:")) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					startActivity(intent);
					return true;
				} else {
					return false;
				}
			}		
		});
		
		webView.setWebChromeClient(new WebChromeClient());

		mLlError.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				webView.reload();
			}
		});
		mLlError.setVisibility(View.GONE);
		synCookies(this,CommonData.LOGIN_GOTO_URL,modifyMobileUrl);
		webView.loadUrl(modifyMobileUrl);
	}
	
	public static void synCookies(Context context, String url, String anotherUrl) {
		String myCookies = "";
		if (!TextUtils.isEmpty(CommonData.SESSIONID) && CommonData.SESSIONID.startsWith("[")
				&& CommonData.SESSIONID.endsWith("]")) {
			myCookies = CommonData.SESSIONID.substring(1, CommonData.SESSIONID.length() - 1);
		}
		CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
		cookieSyncManager.sync();
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		if (!TextUtils.isEmpty(myCookies)) {
			String[] datas = myCookies.split(",");
			for (String data : datas) {
				cookieManager.setCookie(url, data);
				cookieManager.setCookie(anotherUrl, data);
			}
		}
		CookieSyncManager.getInstance().sync();
	}

	// 判断手机格式是否正确
	public boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		Matcher m = p.matcher(mobiles);

		return m.matches();
	}

	class CheckOldMobile extends AsyncTask<Void, Void, Void> {
		private String mCode;// 短信验证码
		private String newphone;// 新手机号
		private String mFailLog;
		private CheckOldMobileClass dateMobileClass = new CheckOldMobileClass();

		public CheckOldMobile(String mCode, String newphone) {
			this.mCode = mCode;
			this.newphone = newphone;
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			RequestObject requestObjectMobileObject = new RequestObject();
			requestObjectMobileObject.method = "appChangeMobile";
			requestObjectMobileObject.map.put("code", mCode);
			requestObjectMobileObject.map.put("newMobile", newphone);

			String requestMobileUrl = RequestBuilder.build(requestObjectMobileObject);
			try {
				IjConnect.doRequest(requestMobileUrl, dateMobileClass);
				if (dateMobileClass.code == null) {
					mFailLog = getResources().getString(R.string.loaddata_exception);
				} else if (!dateMobileClass.code.equals(CommonData.RESULT_SUCCESS)) {
					mFailLog = dateMobileClass.msg;
				}
			} catch (Exception e) {
				// TODO: handle exception
				mFailLog = getResources().getString(R.string.loaddata_exception);
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (!TextUtils.isEmpty(mFailLog)) {
				showToast(mFailLog);
				dismissProgressDialog();
			} else {
				if (dateMobileClass.code != null && dateMobileClass.code.equals(CommonData.RESULT_SUCCESS)) {
					// TODO GET Verification code
					md5UserBaseId = dateMobileClass.md5UserBaseId;
					if (!TextUtils.isEmpty(dateMobileClass.newPhone)) {
						newMobile = dateMobileClass.newPhone;

					}
					dismissProgressDialog();
					showToast(dateMobileClass.msg);
					Intent intent = new Intent(UpdatePhoneActivity.this, BindPhoneNumberActivity.class);
					intent.putExtra("md5UserBaseId", md5UserBaseId);
					intent.putExtra("newMobile", newMobile);
					startActivity(intent);
				}
			}
		}

	}
	
	@Override
	protected void onDestroy() {
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeSessionCookie();
		CookieSyncManager.getInstance().sync();
		super.onDestroy();
	}
}
